package com.app.controller;

import com.app.common.FormStatusTool;
import com.app.model.*;
import com.app.service.*;
import com.app.util.CommonHelp;
import com.app.util.Result;
import com.app.util.TokenUtils;
import com.app.vo.CategoryVo;
import com.app.vo.FormVo;
import com.app.vo.ScoreVo;
import com.app.vo.UserVo;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

@RestController
@Controller
@RequestMapping("/api")
public class UserBehindController {
    @Autowired
    private AdminUserService adminUserService;
    @Autowired
    private UserService userService;
    @Autowired
    private FormService formService;
    @Autowired
    private ScoresService scoresService;


    /**
     * 查询问题列表
     *
     * @param request
     * @return
     */
    @GetMapping("/getBehindUserList")
    public Result<Object> getBehindUserList(
            HttpServletRequest request, UserModel userModel) {
        String token = request.getHeader("authori-zation");
        if (token == null) {
            return Result.error(405, "token不存在");
        }
        String userId = TokenUtils.verify(token);
        if (userId.equals("false")){
            return Result.error(405,"token已过期");
        }
        AdminUserModel user = adminUserService.getUserByUserId(Integer.valueOf(userId));
        if (user == null) {
            return Result.error(406, "用户不存在");
        }
        Page<UserModel> userModelPage = userService.getUserPage(userModel);
        UserVo vo = new UserVo();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        for (int i = 0; i < userModelPage.getRecords().size(); i++) {

            ScoresModel scoresModel = scoresService.getScoreByUserId(userModelPage.getRecords().get(i).getId());
            if(scoresModel!=null)
            {
                userModelPage.getRecords().get(i).setScare(scoresModel.getAfterScore());
            }else {
                userModelPage.getRecords().get(i).setScare(0);
            }

            String crtTime = sdf.format(userModelPage.getRecords().get(i).getCrtTime());
            userModelPage.getRecords().get(i).setCrtTimeText(crtTime);
        }


        vo.setList(userModelPage.getRecords());
        vo.setCount((int)userModelPage.getTotal());
        return Result.success(vo);
    }

    /**
     * 用户数据编辑
     *
     * @param model
     * @param request
     * @return
     */
    @PostMapping("/editBehindUser")
    public Result<Object> editBehindUser(
            @RequestBody UserModel model,
            HttpServletRequest request) {
        String token = request.getHeader("authori-zation");
        if (token == null) {
            return Result.error(405, "token不存在");
        }
        String userId = TokenUtils.verify(token);
        if (userId.equals("false")){
            return Result.error(405,"token已过期");
        }
        AdminUserModel user = adminUserService.getUserByUserId(Integer.valueOf(userId));
        if (user == null) {
            return Result.error(406, "用户不存在");
        }
        if (model.getId() != null && model.getId() > 0) {
            model.setUpTime(CommonHelp.getNowTimestamp());
            userService.update(model);
        } else {
            model.setCrtTime(CommonHelp.getNowTimestamp());
            userService.insert(model);
        }
        return Result.success("操作成功");
    }


    /**
     * 用户详情
     *
     * @param request
     * @return
     */
    @GetMapping("/getBehindUser")
    public Result<Object> getBehindUser(
            HttpServletRequest request, Integer id,Integer page,Integer limit) {
        String token = request.getHeader("authori-zation");
        if (token == null) {
            return Result.error(405, "token不存在");
        }
        String userId = TokenUtils.verify(token);
        if (userId.equals("false")){
            return Result.error(405,"token已过期");
        }
        AdminUserModel user = adminUserService.getUserByUserId(Integer.valueOf(userId));
        if (user == null) {
            return Result.error(406, "用户不存在");
        }

        Page<ScoresModel> scoresModelPage = scoresService.getPageScoresById(page,limit,id);
        UserVo vo = new UserVo();
        ScoreVo scoreVo = new ScoreVo();
        if(scoresModelPage.getRecords()!=null&&scoresModelPage.getRecords().size()>0)
        {
            for (int i = 0; i < scoresModelPage.getRecords().size(); i++) {
                for (int j = 0; j < FormStatusTool.STATUS_VO_LIST.size(); j++) {
                    if(scoresModelPage.getRecords().get(i).getOperateType().equals(FormStatusTool.STATUS_VO_LIST.get(j).getValue()))
                    {
                        scoresModelPage.getRecords().get(i).setOperateTypeText(FormStatusTool.STATUS_VO_LIST.get(j).getName());
                    }
                }
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                if (scoresModelPage.getRecords().get(i).getCrtTime() != null) {
                    String crtTime = sdf.format(scoresModelPage.getRecords().get(i).getCrtTime());
                    scoresModelPage.getRecords().get(i).setCrtTimeText(crtTime);
                }

            }
        }
        List<FormModel> formModels = formService.getModelByUserId(id);
        scoreVo.setList(scoresModelPage.getRecords());
        scoreVo.setCount((int)scoresModelPage.getTotal());
        vo.setForm(scoreVo);
        ScoresModel scoresModel = scoresService.getScoreByUserId(id);
        if(scoresModel!=null)
        {
            vo.setScore(scoresModel.getAfterScore());
        }else {
            vo.setScore(0);
        }
        vo.setAllFormCount(formModels.size());
        vo.setThisFormCount(formModels.size());
        return Result.success(vo);
    }

    /**
     * 用户修改积分
     *
     * @param request
     * @return
     */
    @GetMapping("/edisBehindUserScore")
    public Result<Object> edisBehindUserScore(
            HttpServletRequest request, Integer id,Integer score,Integer integralType) {
        String token = request.getHeader("authori-zation");
        if (token == null) {
            return Result.error(405, "token不存在");
        }
        String userId = TokenUtils.verify(token);
        if (userId.equals("false")){
            return Result.error(405,"token已过期");
        }
        AdminUserModel user = adminUserService.getUserByUserId(Integer.valueOf(userId));
        if (user == null) {
            return Result.error(406, "用户不存在");
        }
        ScoresModel scoresModel = scoresService.getScoreByUserId(id);
        int fen = 0;
        if(scoresModel!=null)
        {
            fen = scoresModel.getAfterScore();
        }

        ScoresModel newScores = new ScoresModel();
        newScores.setCrtTime(CommonHelp.getNowTimestamp());
        newScores.setUserId(id);
        newScores.setScore(score);
        newScores.setOperateType(integralType);
        newScores.setAfterScore(score+fen);
        scoresService.insert(newScores);
        return Result.success("操作成功");
    }
    /**
     * 根据ID查询用户
     *
     * @param request
     * @return
     */
    @GetMapping("/getBehindUserById")
    public Result<Object> getBehindUserById(
            HttpServletRequest request, Integer id) {
        String token = request.getHeader("authori-zation");
        if (token == null) {
            return Result.error(405, "token不存在");
        }
        String userId = TokenUtils.verify(token);
        if (userId.equals("false")){
            return Result.error(405,"token已过期");
        }
        AdminUserModel user = adminUserService.getUserByUserId(Integer.valueOf(userId));
        if (user == null) {
            return Result.error(406, "用户不存在");
        }
        UserModel userModel = userService.getUserById(id);
        return Result.success(userModel);
    }

    /**
     * 用户修改积分
     *
     * @param request
     * @return
     */
    @GetMapping("/userScoreEmpty")
    public Result<Object> userScoreEmpty(
            HttpServletRequest request, String ids) {
        String token = request.getHeader("authori-zation");
        if (token == null) {
            return Result.error(405, "token不存在");
        }
        String userId = TokenUtils.verify(token);
        if (userId.equals("false")){
            return Result.error(405,"token已过期");
        }
        AdminUserModel user = adminUserService.getUserByUserId(Integer.valueOf(userId));
        if (user == null) {
            return Result.error(406, "用户不存在");
        }
        String str[] = ids.split(",");
        for (int i = 0; i < str.length; i++) {
            ScoresModel scoresModel = scoresService.getScoreByUserId(Integer.parseInt(str[i]));
            ScoresModel newScores = new ScoresModel();
            newScores.setCrtTime(CommonHelp.getNowTimestamp());
            newScores.setUserId(Integer.parseInt(str[i]));
            if(scoresModel==null)
            {
                newScores.setScore(0);
            }else{
                newScores.setScore(scoresModel.getAfterScore());
            }

            newScores.setOperateType(4);
            newScores.setAfterScore(0);
            scoresService.insert(newScores);
        }
        return Result.success("操作成功");
    }



}
